import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({ //全局变量定义
	state: {
		shopCar: []
	},
	getters: {
		totalPrice(state) {
			return state.shopCar.reduce((sum, item) => {
				// 如果商品没有数量字段，则默认为1  
				return sum + (item.price * item.maxcount);
			}, 0).toFixed(2); // 保留两位小数  
		},
	},
	mutations: {
		AddShop(state, data) {
			const index = state.shopCar.findIndex(item => item.id === data.id)
			if (index == -1) {
				state.shopCar.push(data)
			} else {
				state.shopCar.maxcount++
			}
		},
		reduceShop(state, data) {
			const index = state.shopCar.findIndex(item => item.id === data.id)
			if (index >= 0) {
				if (state.shopCar[index].maxcount == 0) {
					state.shopCar[index].maxcount = 0
				} else {
					state.shopCar[index].maxcount--
				}
			}
		},
		GenerateOrder(state) {
			// console.log(this.getters.totalPrice);
			//生成订单
			uni.request({
				url:'http://192.168.137.23:8002/admin/addorder',
				method:'POST',
				data:{
					order_num: Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000,
					address_id: 1,
					food_totalprice: this.getters.totalPrice,
					username: uni.getStorageSync("name")
				},
				success(ress) {
					console.log(res.data);
				},
				fail(error) {
					console.log(error);
				}
			})
		}
	}
})
export default store